import { useAuthStore } from "@/store/modules/auth.js";
import { router, LOGIN_PATH } from "./index.js";
import {
  getStorage,
  setStorage,
  removeStorage,
} from "@/utils/storage/index.js";
const NAVIGATE_TYPE_LIST = [
  "navigateTo",
  "redirectTo",
  "reLaunch",
  "switchTab",
];

/**
 * 添加路由拦截器
 */
export function routerInterceptor() {
  NAVIGATE_TYPE_LIST.forEach((item) => {
    uni.addInterceptor(item, {
      // 跳转前拦截
      invoke: (args) => {
        if (args.url === "/pages/login/login") return args;

        const authStore = useAuthStore();
        if (!authStore.isLogin) {
          let token = getStorage("TOKEN") || null;
          authStore.setToken(token);
        }
        if (authStore.permissions == 0) {
          authStore.getInfo();
        }
        if (authStore.isLogin) return args;
        uni.showModal({
          title: "提示",
          content: "登陆失效，请重新登陆",
          success: function (res) {
            if (res.confirm) {
              authStore.setToken(null);
              router.reLaunch({ path: LOGIN_PATH });
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
        return false;
      },
    });
  });
}

/**
 * 移除路由拦截器
 */
export function routerRemoveInterceptor() {
  NAVIGATE_TYPE_LIST.forEach((item) => {
    uni.removeInterceptor(item);
  });
}
